<template>
  <div class="pie-chart">
    <div class="main-wrapper">
      <div class="content-container">
        <!-- 标题区域 -->
        <div class="header-title">
          <div class="chart-title">各类薪酬占比</div>
        </div>

        <!-- 控件区域 -->
        <div class="controls-container">
          <el-row :gutter="10" align="middle">
            <el-col :span="6">
              <el-select
                v-model="selectedDistrict"
                placeholder="请选择区县"
                style="width: 100%"
                @change="handleDistrictChange"
                clearable
              >
                <el-option
                  v-for="district in districtList"
                  :key="district"
                  :label="district"
                  :value="district"
                />
              </el-select>
            </el-col>
            <el-col :span="11">
              <el-select
                v-model="selectedGrid"
                placeholder="请选择网格"
                style="width: 100%"
                @change="handleGridChange"
                clearable
                :disabled="!selectedDistrict || selectedDistrict === '全市'"
              >
                <el-option
                  v-for="grid in gridOptions"
                  :key="grid"
                  :label="grid"
                  :value="grid"
                />
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-date-picker
                v-model="pieChartSelectedDate"
                type="month"
                value-format="YYYY-MM"
                format="YYYY-MM"
                placeholder="选择月份"
                :picker-options="pickerOptions"
                style="width: 100%"
                @change="handleDateChange"
                :disabled-date="disabledDate"
              />
            </el-col>
          </el-row>
        </div>

        <!-- 图表和图例区域 -->
        <div v-if="hasData" class="chart-legend-layer">
          <!-- 图表容器 -->
          <div class="chart-container">
            <div :key="chartKey" ref="chart" class="chart" />
          </div>

          <!-- 图例区域 -->
          <div class="legend-container">
            <div
              v-for="item in sortedLegendData"
              :key="item.name"
              class="legend-item"
            >
              <div
                class="legend-color"
                :style="{ backgroundColor: getColorForLegend(item.name) }"
              />
              <div class="legend-text">
                {{ item.name }} ({{ formatCurrency(item.value) }})
              </div>
            </div>
          </div>
        </div>
        <div v-else class="no-data-placeholder">
          <!-- <el-empty description="暂无数据" /> -->
           <div class="no-data-text">暂无数据</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { ElDatePicker, ElSelect, ElOption, ElRow, ElCol } from "element-plus";
import { getGridName } from "@/api/dwxc/income";
import { getSalaryPercentage } from "@/api/dwxc/salary"; // 引入新接口

export default {
  components: {
    ElDatePicker,
    ElSelect,
    ElOption,
    ElRow,
    ElCol,
  },
  props: {
    selectedDate: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      isUpdating: false, // 添加标志位防止重复调用
      chartKey: 0, // 用于强制重新渲染图表
      // 区县列表
      districtList: [
        "全市",
        "浔阳区",
        "濂溪区",
        "柴桑区",
        "瑞昌市",
        "共青城",
        "庐山市",
        "武宁县",
        "修水县",
        "永修县",
        "德安县",
        "都昌县",
        "湖口县",
        "彭泽县",
      ],
      // 区县名称映射表（显示名称 -> 接口参数名称）
      districtNameMap: {
        浔阳区: "浔阳",
        濂溪区: "濂溪",
        柴桑区: "柴桑",
        瑞昌市: "瑞昌",
        共青城: "共青",
        庐山市: "庐山",
        武宁县: "武宁",
        修水县: "修水",
        永修县: "永修",
        德安县: "德安",
        都昌县: "都昌",
        湖口县: "湖口",
        彭泽县: "彭泽",
      },
      selectedDistrict: "全市", // 默认选中"全市"
      selectedGrid: "", // 选中的网格
      gridOptions: [], // 网格选项列表
      chartInstance: null,
      salaryChartData: [], // 环形图数据
      pieChartSelectedDate: this.selectedDate, // 使用父组件传入的日期
      chartColors: [
        "#66B2FF",
        "#5CD6D6",
        "#99FF99",
        "#FFD700",
        "#FFA07A",
        "#FF6347",
        "#BA55D3",
        "#8A2BE2",
        "#40E0D0",
        "#FF69B4",
        "#20B2AA",
        "#FF8C00",
        "#8B008B",
        "#32CD32",
      ],
      // 日期选择器配置，禁止选择当前月之后的日期
      pickerOptions: {
        disabledDate: (time) => {
          const now = new Date();
          const firstDayOfMonth = new Date(
            now.getFullYear(),
            now.getMonth(),
            1
          );
          return time.getTime() >= firstDayOfMonth.getTime();
        },
      },
    };
  },
  computed: {
    sortedLegendData() {
      // 按值从大到小排序图例数据
      // return [...this.salaryChartData]
      //   .filter((item) => item.value > 0)
      //   .sort((a, b) => b.value - a.value);
      // 按薪酬区间数值大小排序，而不是按人数排序
      return [...this.salaryChartData]
        .filter((item) => item.value > 0)
        .sort((a, b) => {
          // 提取区间起始值进行排序
          const getRangeStart = (name) => {
            if (name === "0-1000" || name === "1000以下") return 0;
            const match = name.match(/^(\d+)-/);
            return match ? parseInt(match[1]) : 0;
          };
          
          return getRangeStart(a.name) - getRangeStart(b.name);
        });
    },
    hasData() {
      // 判断是否有有效数据
      return this.salaryChartData && 
             this.salaryChartData.some(item => item.value > 0);
    }
  },
  watch: {
    selectedDate: {
      handler(newVal) {
        // 只有当外部传入的日期与当前日期不同时才更新
        if (newVal !== this.pieChartSelectedDate) {
          this.pieChartSelectedDate = newVal;
          this.loadChartData(this.selectedDistrict, this.selectedGrid);
        }
      },
      immediate: true, // 设置为true，确保初始化时也能触发
    },
    hasData: {
      handler(newVal, oldVal) {
        // 当从无数据变为有数据时，确保图表重新初始化
        if (newVal && !oldVal) {
          this.$nextTick(() => {
            // 增加 chartKey 强制重新渲染图表DOM
            this.chartKey++;
            this.$nextTick(() => {
              // 等待DOM更新后重新初始化图表
              this.initChart();
              this.updateChart(this.selectedDistrict, this.selectedGrid);
            });
          });
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
      this.loadChartData(this.selectedDistrict, this.selectedGrid);
    });
  },
  methods: {
    disabledDate(time) {
      // Disable current month and future months
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth(); // 0-11

      const selectedDate = new Date(time);
      const selectedYear = selectedDate.getFullYear();
      const selectedMonth = selectedDate.getMonth(); // 0-11 // Disable if selected date is current or future month

      return (
        selectedYear > currentYear ||
        (selectedYear === currentYear && selectedMonth >= currentMonth)
      );
    },
     initChart() {
      // 销毁已存在的图表实例
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }
      
      // 初始化新的图表实例
      if (this.$refs.chart) {
        this.chartInstance = echarts.init(this.$refs.chart);
        window.addEventListener("resize", this.handleResize);
      }
    },

    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },

    beforeDestroy() {
      window.removeEventListener("resize", this.handleResize);
    },

    /**
     * 处理区县下拉框变化
     */
    handleDistrictChange(district) {
      console.log("选中的区县：", district);
      this.selectedGrid = ""; // 清空网格选择
      this.gridOptions = []; // 清空网格选项

      if (district && district !== "全市") {
        // 使用映射后的区县名称去查询网格
        const mappedCounty = this.districtNameMap[district] || district;
        console.log(
          "请求接口：/gridManager/getGridName?county=" + mappedCounty
        );

        getGridName(mappedCounty)
          .then((res) => {
            console.log("接口返回数据：", res);
            // 根据实际返回的数据结构调整
            if (Array.isArray(res)) {
              this.gridOptions = res;
            } else if (res.data && Array.isArray(res.data)) {
              this.gridOptions = res.data;
            } else {
              this.gridOptions = [];
            }
          })
          .catch((error) => {
            console.error("获取网格失败:", error);
            this.$message.error("获取网格失败: " + (error.message || ""));
            this.gridOptions = [];
          });
      }

      this.loadChartData(district, this.selectedGrid);
    },

    /**
     * 处理网格下拉框变化
     */
    handleGridChange(grid) {
      console.log("选中的网格：", grid);
      this.loadChartData(this.selectedDistrict, grid);
    },

    /**
     * 处理日期变化
     */
    handleDateChange(date) {
      // 通知父组件日期已更改
      this.$emit("handle-date-change", date);
      // 直接调用数据加载，避免通过watch触发
      this.loadChartData(this.selectedDistrict, this.selectedGrid);
    },

    /**
     * 格式化货币显示
     */
    formatCurrency(value) {
      return `${Number(value).toLocaleString("zh-CN", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })}元`;
    },

    /**
     * 加载薪酬数据（从接口获取真实数据）
     * @param {string} district 区县名称
     * @param {string} grid 网格名称
     */
    loadChartData(district, grid) {
       // 添加防重复调用机制
      if (this.isUpdating) {
        return;
      }
      
      this.isUpdating = true;

      // 格式化日期为接口需要的格式 (YYYY-MM)
      let formattedDate = "";
      if (this.pieChartSelectedDate) {
        if (typeof this.pieChartSelectedDate === "string") {
          // 如果是字符串格式 YYYY-MM-DD，提取 YYYY-MM
          formattedDate = this.pieChartSelectedDate.substring(0, 7);
        } else if (this.pieChartSelectedDate instanceof Date) {
          // 如果是 Date 对象，格式化为 YYYY-MM
          const year = this.pieChartSelectedDate.getFullYear();
          const month = (this.pieChartSelectedDate.getMonth() + 1)
            .toString()
            .padStart(2, "0");
          formattedDate = `${year}-${month}`;
        }
      } else {
        // 默认使用当前月份的上一个月
        const now = new Date();
        const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        formattedDate =
          lastMonth.getFullYear() +
          "-" +
          String(lastMonth.getMonth() + 1).padStart(2, "0");
      }

      // 构造查询参数
      const params = {
        time: formattedDate,
      };

      // 根据选择的维度设置参数
      if (grid) {
        // 如果选择了网格，需要同时传递区县和网格参数
        params.gridName = grid;
        if (district && district !== "全市") {
          const mappedDistrict = this.districtNameMap[district] || district;
          params.district = mappedDistrict;
        } else {
          params.district = "全市";
        }
      } else if (district && district !== "全市") {
        // 如果只选择了区县，则查询区县维度的数据
        const mappedDistrict = this.districtNameMap[district] || district;
        params.district = mappedDistrict;
      } else {
        // 默认查询全市数据
        params.district = "全市";
      }

      console.log("请求参数:", params); // 添加调试日志

      // 调用新接口获取真实数据
      getSalaryPercentage(params)
        .then((res) => {
          console.log("接口返回数据:", res); // 添加调试日志
          const responseData = res.data || res;

          if (responseData && responseData.amountPercentage) {
            // 转换接口数据为 echarts 需要的格式
            const amountPercentage = responseData.amountPercentage;

            // 按照业务逻辑重新分类薪酬项目
            const categorizedData = {
              存量维护: 0,
              新装按次: 0,
              随销收入: 0,
              服务奖罚: 0,
              奖励与补贴: 0,
              其他: 0,
            };

            // 遍历接口数据并按类别归类
            Object.entries(amountPercentage).forEach(([key, value]) => {
              const amount = Number(value.amount);
              switch (key) {
                case "存量维护":
                  categorizedData["存量维护"] += amount;
                  break;
                case "新装按次":
                  categorizedData["新装按次"] += amount;
                  break;
                case "随销收入":
                  categorizedData["随销收入"] += amount;
                  break;
                case "服务奖罚":
                  categorizedData["服务奖罚"] += amount;
                  break;
                case "激励包分配":
                case "金银铜":
                case "补差":
                  categorizedData["奖励与补贴"] += amount;
                  break;
                case "试用期工资":
                case "上门整治服务":
                  categorizedData["其他"] += amount;
                  break;
                default:
                  categorizedData["其他"] += amount;
                  break;
              }
            });

            // 转换为图表需要的格式，过滤掉0值
            const seriesData = Object.entries(categorizedData)
              .map(([name, value]) => ({
                name: name,
                value: value,
              }))
              .filter((item) => item.value > 0);

            this.salaryChartData = seriesData;
          } else {
            this.salaryChartData = [];
          }

          this.updateChart(district, grid);
        })
        .catch((error) => {
          console.error("获取薪酬数据失败:", error);
          console.error(
            "错误详情:",
            error.response || error.request || error.message
          );
          this.$message.error("获取薪酬数据失败: " + (error.message || ""));
          this.salaryChartData = [];
          this.updateChart(district, grid);
        })
        .finally(() => {
          // 重置标志位
          this.isUpdating = false;
        });
    },

    /**
     * 获取图例项对应的颜色
     */
    getColorForLegend(name) {
      const index = this.sortedLegendData.findIndex(
        (item) => item.name === name
      );
      return this.chartColors[index % this.chartColors.length];
    },

    /**
     * 更新环形图显示
     * @param {string} district 当前选中区县
     * @param {string} grid 当前选中网格
     */
    updateChart(district, grid) {
      // 构建标题，包含区县和网格信息
      let title = district;
      if (grid) {
        title += " - " + grid;
      }
      title += " 各类薪酬占比";

      // 先过滤出有效数据（value > 0）
      const validData = this.salaryChartData.filter(item => item.value > 0);

      // 构造图表数据，如果有有效数据则使用，否则显示"无数据"
      const seriesData = validData.length > 0 
        ? validData 
        : [{ name: "暂无数据", value: 1 }];

      const option = {
        backgroundColor: "#ffffff",
        color: this.chartColors,
        title: {
          text: title,
          left: "center",
          show: false, // 隐藏内部标题，使用外部标题
        },
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            const value = this.formatCurrency(params.value);
            return `${params.name}: ${value} (${params.percent}%)`;
          },
          position: 'center' // 添加这一行，使提示框显示在圆心位置
        },
        legend: {
          show: false, // 隐藏默认图例，使用自定义图例
        },
        series: [
          {
            name: "薪酬构成",
            type: "pie",
            radius: ["100%", "40%"], // 增大环形图尺寸
            center: ["50%", "50%"],
            avoidLabelOverlap: true,
            label: {
              show: false,
              position: "outside",
              formatter: "{b}: {d}%",
              fontSize: 12,
              color: "#666",
              distanceToLabelLine: 5,
            },
            labelLine: {
              show: false,
              length: 40,
              length2: 20,
              smooth: 0.2,
              lineStyle: {
                width: 1,
                color: "#999",
              },
            },
            // 直接使用处理好的数据，不再额外过滤
            data: seriesData,
            itemStyle: {
              borderRadius: 6,
              borderColor: "#fff",
              borderWidth: 2,
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            minAngle: 5,
            stillShowZeroSum: false,
          },
        ],
      };

      // 添加检查确保图表实例存在
      if (!this.chartInstance && this.$refs.chart) {
        this.initChart();
      }
      
      if (this.chartInstance) {
        this.chartInstance.setOption(option, true);
        this.chartInstance.resize();
      }
    },
  },
};
</script>

<style scoped>
.no-data-text {
  font-size: 16px;
  color: #909399;
}
/* 添加无数据时的样式 */
.no-data-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.pie-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.main-wrapper {
  width: 100%;
  height: 98%;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  flex: 1;
}

/* 标题区域 */
.header-title {
  padding: 0 0 10px 0;
  margin-bottom: 10px;
  text-align: center;
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 控件区域 */
.controls-container {
  padding: 0 0 15px 0;
  margin-bottom: 15px;
}

/* 图表和图例区域 */
.chart-legend-layer {
  display: flex;
  flex: 0 0 300px; /* 固定高度为300px，避免占用过多空间 */
  gap: 30px;
  margin-bottom: 15px;
}

.chart-container {
  flex: 2;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

.legend-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 12px;
  padding: 10px 0;
  max-width: 300px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 3px 0;
}

.legend-color {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  flex-shrink: 0;
}

.legend-text {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .controls-container {
    flex-direction: column;
    gap: 15px;
  }

  .chart-legend-layer {
    flex-direction: column;
    flex: 0 0 auto; /* 在小屏幕上自适应高度 */
    height: auto;
  }

  .legend-container {
    max-width: 100%;
    margin-top: 20px;
  }

  .district-select {
    width: 250px;
  }
}
</style>
